<?php

namespace App\Http\Controllers\settingcontroller;
use App\Http\Controllers\Controller;
use App\Models\DawnTaskSettings;
use Illuminate\Http\Request;
use App\Pojo\Response;
use App\Exceptions\BusinessException;
use Illuminate\Support\Facades\Auth;

class DawnSettingController extends Controller{
    
    public function getDawnSetting(Request $request){
        $dawnSetting = DawnTaskSettings::where('user_id', Auth::id())->whereNull('deleted_at')->first();
        if(is_null($dawnSetting)){
            throw new BusinessException("请设置打卡任务，才能进行后续操作");
        }
        return Response::success($dawnSetting, "打卡任务已设置");
    }

    public function saveDawnSetting(Request $request){
        $data = $request->validate([
            'default_images' => 'required|boolean',
            'feedbackEnabled' => 'required|boolean',
            'imageCount' => 'required|integer',
            'randomLocation' => 'required|boolean',
        ]);

        $dawnSetting = DawnTaskSettings::where('user_id', Auth::id())->first();
        
        if (!$dawnSetting) {
            // 没有对应的数据 则创建
            $dawnSetting = new DawnTaskSettings();
            $dawnSetting->user_id = Auth::id();
            $dawnSetting->default_images = $data['default_images'];
            $dawnSetting->feedback_enabled = $data['feedbackEnabled'];
            $dawnSetting->image_count = $data['imageCount'];
            $dawnSetting->random_location = $data['randomLocation'];
            $dawnSetting->save();
        }else{
            // 有对应的数据 则更新
            // 更新打卡设置
            $dawnSetting->update([
                'user_id' => Auth::id(),
                'default_images' => $data['default_images'],
                'feedback_enabled' => $data['feedbackEnabled'],
                'image_count' => $data['imageCount'],
                'random_location' => $data['randomLocation']
            ]);
        }

        return Response::success($dawnSetting, "操作成功");
    }
}